/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package deatax;

/**
 *
 * @author nrechten
 */
public class Timer implements Runnable {

    Thread t;
    Runnable rl;
    long tick;
    boolean run;

    public Timer(Runnable rl, long tick) {
        this.rl = rl;
        this.tick = tick;
    }

    public void start(){
        run = true;
        if(t == null){
            t = new Thread(this);
            t.start();
        }
    }

    public void stop(){
        run = false;
    }

    public void run() {
        try {
            skip();
        } catch (InterruptedException ex) {
        }
        t = null;
    }

    public void skip() throws InterruptedException{
        long start = 0;
        while(run){
            start = System.currentTimeMillis();
            rl.run();
            if(System.currentTimeMillis() - start == 0){
                Thread.sleep(tick);
            } else if(tick - (System.currentTimeMillis() - start)  > 0){
                Thread.sleep(tick - (System.currentTimeMillis() - start));
            } else {
                Thread.sleep(tick*tick/(System.currentTimeMillis() - start) - (System.currentTimeMillis() - start)%tick);
            }
        }
    }

}
